<?php
namespace H5\Controller;


use Think\Controller;

use Lcobucci\JWT\Parser;
use Think\Exception;

class WebController extends Controller {

    const TOKEN_KEY_NAME = 'uid';      //jwt token key string 关键值

    /**
     * @var array 两个版本的下载地址
     */
    protected $download = ['ios' =>'https://fir.im/1hmx','android'=>'https://fir.im/sjzh'];

    public function _initialize(){
        $this->assign($this->download);
        //是否显示下载
        $is_show = I('is_show_download',1,'boolval');
        $this->assign('is_show',$is_show);
    }

    public function act() {
        $this->assign('title','活动');

        $act_model = M("Activity");
        $id = I("id", 0, 'intval');
        $where['id'] = $id;
        $where['act_status'] = array('GT', 0);
        $activity = $act_model->where($where)->order(array("update_time" => "desc"))->field("id,act_title,act_content,act_pic,start_time,end_time")->find();

        if ($activity) {
            $end_time = strtotime($activity['end_time']);
            $activity['is_expire'] = $end_time > time() ? 0 : 1;

            $activity['start_time'] = date('Y.m.d',strtotime($activity['start_time']));
            $activity['end_time'] = date('Y.m.d',strtotime($activity['end_time']));

            //过滤html
            $activity['act_pic'] = qiniu_mirror_image_url_act($activity);
            $uid = $this->parseTokenUID();
            $where = ['uid' => $uid, 'act_id' => $id];

            //判断用户是否收藏活动
            $is_favorated = D('UserActivityFavorites')->where($where)->find();
            if(empty($is_favorated)){
                $activity['is_add_favarate'] = 0;
                $activity['add_favorite_url'] = U('/ApiWF/Activity/getFavor',['token'=>I('token'),'act_id'=>$id,'type'=>1]);
            }else {
                $activity['is_add_favarate'] = 1;
            }

            //判断用户是否参加活动
            $is_participate = M('UsersActivity')->where($where)->find();
            $activity['is_join'] = empty($is_participate) ? 0 : 1;





            $this->assign($activity);
            $this->display('act');
            //http://www.worldflower.zhou/H5/Web/act?id=31&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiI5OTMwIiwiZXhwIjoxNDg2NzMzNjY4LCJpc3MiOiJ3b3JsZGZsb3dlci5sb29uZ3Npbi5jb20ifQ.ivuLODEXYUJnjxCacaNiUm41qxrXHUVq_9EdpQcMCUs
        }
        else {
            $this->assign('message','活动不存在');

            return $this->display('no_item');
        }
    }
    //废弃新手任务和活动详情一致;
    public function task() {
        $this->assign('title','新手任务');

        $act_model = M("Activity");
        $id = I("id", 0, 'intval');
        $where['id'] = $id;
        $where['act_status'] = array('GT', 0);
        $activity = $act_model->where($where)->order(array("update_time" => "desc"))->field("id,act_title,act_content,act_pic,start_time,end_time")->find();
        if ($activity) {

            $activity['start_time'] = date('Y.m.d',strtotime($activity['start_time']));
            $activity['end_time'] = date('Y.m.d',strtotime($activity['end_time']));

            //过滤html
            $activity['act_pic'] = qiniu_mirror_image_url_act($activity);

            $this->assign($activity);
            $this->display('task');
            //http://www.worldflower.zhou/H5/Web/task?77=31&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiI5OTMwIiwiZXhwIjoxNDg2NzMzNjY4LCJpc3MiOiJ3b3JsZGZsb3dlci5sb29uZ3Npbi5jb20ifQ.ivuLODEXYUJnjxCacaNiUm41qxrXHUVq_9EdpQcMCUs
        }
        else {
            $this->assign('message','任务不存在');
            return $this->display('no_item');
        }

    }

    public function merch() {
        $this->assign('title','商户');

        $uid = $this->parseTokenUID();
        $mid = I('id', 0, 'intval');
        $merch_info = D('MerchView')->where(['id' => $mid,'Merch.merch_status'=>['GT',0]])->find();
        if (empty($merch_info)) {
            $this->assign('message','商户不存在');

            return $this->display('no_item');
        }
        $merch_info['merch_pics'] = qiniu_mirror_image_url_merchant($merch_info);

        $where['goods_status'] = ['GT',0];
        $where['mid'] = $mid;
        $goods = D('MerchGoods')->where($where)->order('create_time desc')->select();
        foreach ($goods as $key => $good) {
            $goods[$key]['goods_pics'] = qiniu_mirror_image_url_merch_good($good);
            htmlStringToPlainStirngArray($goods[$key], 'goods_content');
        }

        $where = [
            'status' => ['GT', 0],
            'mid' => $mid,
        ];

        $comments = D('MerchCommentsView')->where($where)->order('create_time desc')->select();
        foreach ($comments as $key => $vo) {
            $avatar = qiniu_mirror_image_url($vo['avatar']);
            if(is_numeric($vo['content'] and $vo['content']>10000000000000)){
                $comments[$key]['content'] = sprintf('%.13e',$vo['content']);
            }
            $comments[$key]['avatar'] = $avatar;
            $comments[$key]['create_time'] = friendlyDate($vo['create_time']);
        }
        //是否收藏
        $where = [
            'uid' => $uid,
            'mid' => $mid
        ];
        $res = D('UserMerchFavorites')->where($where)->find();
        $merch_info['is_favorite'] = empty($res) ? 0 : 1;

        $praise = D('MerchUserPraises')->where($where)->find();


        $merch_info['is_praise'] = empty($praise) ? 0 : 1;

        $this->assign($merch_info);
        $this->assign('goods',$goods);
        $this->assign('comments',$comments);


        $this->display('merch');
    }

    public function goods() {
        $this->assign('title','商品');


        $goods_id = I('id',0,'intval');

        $good_info = D('MerchGoods')->where(['id' => $goods_id,'goods_status'=>['GT',0]])->find();
        if (empty($good_info)) {
            $this->assign('message','商品不存在');

            return $this->display('no_item');
        }
        $smeta = json_decode($good_info['goods_pics'],true);
        $good_info['slides'] = $smeta['photo'];

        $good_info['thumb_img'] = qiniu_mirror_image_url_merch_good($good_info);
        $this->assign($good_info);

        $this->display('goods');
    }


    public function news(){
        $this->assign('title','资讯');

        //参数
        $id = I('id', 0, 'intval');
        $where = compact('id');
        $where['post_status'] = 1;
        $data = D('Posts')->where($where)->find();
        if (empty($data)) {
            $this->assign('message','资讯不存在');
            return $this->display('no_item');
        }
        $data['smeta'] = qiniu_mirror_image_url_post($data);
        $this->assign($data);
        $this->display('news');
    }


    protected function parseTokenUID($tokenString = null)
    {
        $tokenString = empty($tokenString)? I('token') : $tokenString;

        if(empty($tokenString)){
            $this->assign('no_token',1);
            return 0;
        }

        try {
            $token = (new Parser())->parse($tokenString); // Parses from a string
            if (!APP_DEBUG) {
                //验证token来源是否合法
                $host = $_SERVER['HTTP_HOST'];
                $issuer = $token->getClaim('iss');
                if ($issuer !== $host) {
                    return $this->error('跨域token!');
                }

                //验证token失效时间
                $expires_time = $token->getClaim('exp');
                $now_time = time();
                if ($now_time > $expires_time) {
                    return $this->error('token已经过期请重新登录!');
                }
            }
            //返回uid;
            $uid = $token->getClaim(self::TOKEN_KEY_NAME);

            return $uid;
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function comment_page(){
        $merch_id = I('merch_id',0,'intval');


        $res = D('MerchComments')->where(['mid'=>$merch_id])->Count();
        if(!$res){
            $this->assign('message','商家还没有评论消息');
            return $this->display('no_item');
        }



        $this->assign('merch_id',$merch_id);
        $this->display();
    }
}